package com.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.common.utils.CurrentRoleUtils;
import com.common.utils.bean.BeanUtils;
import com.common.utils.uuid.IdUtils;
import com.project.domain.bo.ProjectTabListBo;
import com.project.domain.entity.BizProjectInSchool;
import com.project.domain.entity.zxProject.BizZxProject;
import com.project.mapper.ProjectInSchoolMapper;
import com.project.service.IBizProjectInSchoolService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

@Service
public class ProjectInSchoolServiceImpl implements IBizProjectInSchoolService {

    @Autowired
    private ProjectInSchoolMapper bizProjectInSchoolMapper;

    @Autowired
    private ProjectInitServiceImpl projectInitService;

    /**
     * 查询校内课题从
     *
     * @param ID 校内课题从主键
     * @return 校内课题从
     */
    @Override
    public BizProjectInSchool selectBizProjectInSchoolByID(String ID)
    {
        return bizProjectInSchoolMapper.selectById(ID);
    }

    /**
     * 查询校内课题从列表
     *
     * @param bizProjectInSchool 校内课题从
     * @return 校内课题从
     */
    @Override
    public List<BizProjectInSchool> selectBizProjectInSchoolList(BizProjectInSchool bizProjectInSchool)
    {
//        QueryWrapper<BizProjectInSchool> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq(StringUtils.isNotBlank(bizProjectInSchool.getProjectId()), "PROJECT_ID", bizProjectInSchool.getProjectId());
        return bizProjectInSchoolMapper.selectBizProjectInSchoolList(bizProjectInSchool.getProjectId());
    }

    /**
     * 新增校内课题
     *
     * @param bizProjectInSchool 校内课题从
     * @return 结果
     */
    @Override
    public int insertBizProjectInSchool(BizProjectInSchool bizProjectInSchool)
    {
        return bizProjectInSchoolMapper.insert(bizProjectInSchool);
    }

    /**
     * 修改校内课题
     *
     * @param bizProjectInSchool 校内课题从
     * @return 结果
     */
    @Override
    public int updateBizProjectInSchool(BizProjectInSchool bizProjectInSchool)
    {
        return bizProjectInSchoolMapper.updateById(bizProjectInSchool);
    }

    /**
     * 批量删除校内课题
     *
     * @param IDs 需要删除的校内课题从主键
     * @return 结果
     */
    @Override
    public int deleteBizProjectInSchoolByIDs(String[] IDs)
    {
        return bizProjectInSchoolMapper.deleteBatchIds(Arrays.asList(IDs));
    }

    /**
     * 删除校内课题从信息
     *
     * @param ID 校内课题从主键
     * @return 结果
     */
    @Override
    public int deleteBizProjectInSchoolByID(String ID)
    {
        return bizProjectInSchoolMapper.deleteById(ID);
    }

    /**
     * 新增校内课题List：分为两种情况：
     * 1保存课题页签或保存并通过：普通保存不会新建项目（submitType ！= 2）；保存并通过：管理员时新建秘书不新建
     * 2.管理员审核通过其他页签但整个项目都通过审核了：submitType为空（方法里强行写为2）
     * @param projectTabListBo 校内课题
     * @return 结果
     */
    @Override
    public String saveKetiList(ProjectTabListBo<BizProjectInSchool> projectTabListBo)
    {
        String res = "保存成功！";
        try{
            String proId = projectTabListBo.getProId();
            //获取主项目信息
            BizZxProject mainProBase = projectInitService.zxDetail(proId);
            if (mainProBase != null){
                //先删除
                deleteByProId(proId);

                List<BizProjectInSchool> bizProjectInSchoolList = projectTabListBo.getSlaveTableList();
                if(bizProjectInSchoolList != null && bizProjectInSchoolList.size() > 0){
                    for(int m = 0;m<bizProjectInSchoolList.size();m++){
                        BizProjectInSchool bizProjectInSchool = bizProjectInSchoolList.get(m);
                        //处理金额
                        BigDecimal newFee = bizProjectInSchool.getProjectFee().multiply(new BigDecimal("10000"));
                        //如果主项目已审核，每条课题数据新建一个项目
                        //如果是保存并通过，且当前角色是管理员，那整个项目都通过了
                        if(projectTabListBo.getSubmitType() != null && projectTabListBo.getSubmitType()== 2 && CurrentRoleUtils.getCurrentRoleKey().equals("biz_kycgly")){
                            BizZxProject newZxPro = new BizZxProject();
                            //主项目的数据都映射到新的项目中
                            BeanUtils.copyProperties(mainProBase,newZxPro);
                            //根据课题信息修改部分字段
                            String uuID = IdUtils.simpleUUID();
                            newZxPro.setId(uuID);
                            newZxPro.setName(bizProjectInSchool.getProjectName());
                            newZxPro.setUnitId(bizProjectInSchool.getProjectUnit());
                            newZxPro.setChargerName(bizProjectInSchool.getProjectLeader());
                            newZxPro.setChargerCode(bizProjectInSchool.getProjectLeaderPersonid());
//                            newZxPro.setFeeAuthorize(newFee.toString());
                            newZxPro.setFeeAuthorize( bizProjectInSchool.getProjectFee().toString());

                            newZxPro.setLevelType("2");//课题类型固定是课题
                            newZxPro.setSubjectNature("ourSchool");//课题性质固定是依托本校
                            newZxPro.setUpItemId(mainProBase.getId());
                            newZxPro.setUpItemName(mainProBase.getName());
                            newZxPro.setRelyingProjectLeader(mainProBase.getChargerName());

                            newZxPro.setAuthorpids(bizProjectInSchool.getProjectLeaderPersonid());//成员id取负责人id
                            newZxPro.setAuthorunitids(bizProjectInSchool.getProjectUnit());//成员单位取负责人单位

                            //新项目的审核状态为 待完善
                            newZxPro.setCheckstatus("-2");
                            newZxPro.setCompletedatastatus("notComplete");
                            newZxPro.setProcessInstanceId("");

                            String insertRes = String.valueOf(projectInitService.saveZxProInfos(newZxPro,"all"));
                            if(insertRes.contains("成功")){
                                bizProjectInSchool.setCreatFlag("yes");
                                bizProjectInSchool.setSubjectId(uuID);
                            }
                        }

                        bizProjectInSchool.setOrderId((long)m+1);
                        bizProjectInSchool.setProjectFee(newFee);
                        bizProjectInSchoolMapper.insert(bizProjectInSchool);
                    }
                }
            }
        }catch (Exception exception){
            res = "保存课题信息失败！" + exception.getMessage();
        }

        return res;
    }

    /**
     * 根据项目号批量删除
     * @param proId
     * @return
     */
    public String deleteByProId(String proId){
        String res = "删除成功！";
        try{
            QueryWrapper<BizProjectInSchool> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("PROJECT_ID",proId);
            bizProjectInSchoolMapper.delete(queryWrapper);
        }catch (Exception exception){
            res = "删除失败！" + exception.getMessage();
        }

        return res;
    }

    /**
     * 纵向项目通过审核后课题都新建为项目，直接调用保存课题的方法（先删掉旧数据，再根据状态处理）
     * @param proId
     */
    public String changeInSchoolInfo(String proId){
        String res = "课题相关成功";
        try{
            BizProjectInSchool bizProjectInSchool = new BizProjectInSchool();
            bizProjectInSchool.setProjectId(proId);
            List<BizProjectInSchool> inSchoolList = this.selectBizProjectInSchoolList(bizProjectInSchool);
            if(inSchoolList != null && inSchoolList.size()>0){
                //获取项目基础信息
                ProjectTabListBo<BizProjectInSchool> projectTabListBo = new ProjectTabListBo<>();
                projectTabListBo.setSlaveTableList(inSchoolList);
                projectTabListBo.setProId(proId);
                projectTabListBo.setSubmitType(2);
                res = this.saveKetiList(projectTabListBo);
            }
        }catch (Exception exception){
            res = exception.getMessage();
        }
        return res;
    }
}
